use mlibs::periph::adc::ADC1;
use mlibs::periph::config_io;
use mlibs::periph::dma::{DmaBuf, DMA1};
use mlibs::periph::gpio::PA;
use mlibs::periph::rcc::RCC;
use mlibs::periph::{config_adc, config_dma, AFIO};

#[config_adc(ADC1_CH3_CH4_CH5)]
struct ADCTest;

#[config_io(IN3_PA3_ANALOG, IN4_PA4_ANALOG, IN5_PA5_ANALOG)]
struct ADCPin;

#[config_dma(DMA1_CH1_SIZE16)]
struct ADCDma;

static mut DMA_BUF: DmaBuf<u16, 3> = DmaBuf::default();

pub fn init() {
    RCC.apb2enr.modify(|_, w| w.afioen().enabled());
    AFIO.mapr.write(|w| w.swj_cfg().variant(2));

    ADCPin.init();
    ADCTest.init();
    ADCDma.init_rcc();

    unsafe {
        ADCDma.read_with_circ(ADC1.dr.as_ptr() as u32, DMA_BUF.as_mut_ref());
    }
    ADCTest.start();
}

pub fn in3() -> u16 {
    unsafe {
        let p = DMA_BUF.as_ptr();
        p.read_volatile()
    }
}

pub fn in4() -> u16 {
    unsafe { DMA_BUF.as_ptr().add(1).read_volatile() }
}

pub fn in5() -> u16 {
    unsafe { DMA_BUF.as_ptr().add(2).read_volatile() }
}
